package com.ark.cloud.javacallnative.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author fukun
 * @create 2021/10/18  下午2:41
 * @description 创建线程池
 */
@Configuration
@EnableAsync
public class TaskExecutePool {

    @Autowired
    TaskThreadPoolConfig taskThreadPoolConfig;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数大小
        threadPoolTaskExecutor.setCorePoolSize(taskThreadPoolConfig.getCorePoolSize());
        // 最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(taskThreadPoolConfig.getMaxPoolSize());
        // 线程空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(taskThreadPoolConfig.getKeepAliveSeconds());
        // 任务队列容量(阻塞队列)
        threadPoolTaskExecutor.setQueueCapacity(taskThreadPoolConfig.getQueueCapacity());
        // 线程名字前缀
        threadPoolTaskExecutor.setThreadNamePrefix(taskThreadPoolConfig.getNamePrefix());
        // 当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
